package com.script

import com.CustomScript
import com.FileCrcMode
import com.utils.PropertiesUtils
import com.utils.ScriptUtils.appConfig
import com.utils.ScriptUtils.contrastFile
import com.utils.ScriptUtils.isWindow
import com.utils.ScriptUtils.script
import org.apache.logging.log4j.kotlin.logger

script.customScript.add(object : CustomScript {
    override fun onBeforeUpload() {
        super.onBeforeUpload()
        beforeUpload()
    }
})

private fun beforeUpload() {
    val fileCrc = appConfig.fileCrc
    val crcMode = fileCrc.mode
    logger.info("执行最后的上传前工作处理 fileCrcMode=$crcMode")
    if (crcMode == FileCrcMode.NONE) return

    // 执行打包layadcc
    val addOssPush = contrastFile.addOssPush
    val deleteOssPush = contrastFile.deleteOssPush
    if (addOssPush.isNotEmpty() || deleteOssPush.isNotEmpty()) {
        // 将本次上传的文件拷贝到用户临时目录中
        var bucketName = "demoBucketName"
        var rootPath = ""

        // 非内网的模式下获取存在的 bucketName rootPath
//        if (YamlUtil.unpackEnvId > 1) {
//            // 先获取传入的用户数据
//            val userData = appConfig.user[YamlUtil.unpackEnvName]!!
//            if (userData.containsKey("aws")) {
//                val strs = contrastFile.cmdSplit(userData["aws"] as String)
//                for (i in strs.indices step 2) {
//                    if (strs[i] == "bucketName" || strs[i] == "bname") {
//                        bucketName = strs[i + 1]
//                    } else if (strs[i] == "rootPath") {
//                        rootPath = strs[i + 1]
//                    }
//                }
//            }
//        }


        val newPath = appConfig.outDir
//        val newPath = Path(System.getProperty("user.home"), bucketName)
//        if (newPath.exists()) {
//            newPath.deleteRecursively()
//        }
//        newPath.createDirectories()
//
        for (path in addOssPush) {
            println("----------------------------- $path")
            val crc = PropertiesUtils.instance.get(path)
            if (crc != null) {
                val oldPath = path.toAbsolutePath()
//                path.renameWithCrc32(crc, fileCrcMode)
                logger.debug("修改文件名字：${oldPath.absolutePathString} -> ${path.absolutePathString}")
            }
        }

        if (isWindow)
            contrastFile.exec("start", newPath.pathString)
        else contrastFile.exec("open", newPath.pathString)

        logger.info("拷贝结束")
        // 拷贝结束

        if (script.packCmd.isZip) {
            logger.info("压缩资源 暂未实现")
//            local saveFile = luajava . newInstance ("java.io.File", newPath, newPath:getName()..".zip")
//            print("压缩路径："..newPath:getPath())
//            ZipUtils:zipFileList(saveFile:getAbsolutePath(), newPath:getPath(), false)
        }

    }

}